package day21.fefei;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
class ServerTCP {
    public static void main(String[] args) throws Exception {
        System.out.println("服务端启动，等待客服端-----");
        ServerSocket server = new ServerSocket(8088);
        //接收客户端发来的信息  accept用来接收一个客户端
        Socket accept = server.accept();
        System.out.println("接收到一个客户端");
        InputStream is = accept.getInputStream();


        int len = 0;
        byte[] data = new byte[1024];
        while ((len = is.read(data)) != -1) {
            System.out.println("从客户端接收的信息为：" + new String(data, 0, len));
        }
        accept.shutdownInput();
        //在服务端也可以发送信息
        OutputStream os = accept.getOutputStream();

        os.write("我收到了客户端消息".getBytes());
        accept.close();
    }
}

public class ClientTCP {

    public static void main(String[] args) throws Exception {
        //Socket 类创建客户端
        InetAddress localHost = InetAddress.getLocalHost();
        Socket socket = new Socket(localHost, 8088);

        //客户端给服务端发送消息，也可以从服务端接收

        OutputStream os = socket.getOutputStream();
        String sendContent = "你好，服务器";
        os.write(sendContent.getBytes());
        os.flush();
        os.close();

        //接收服务器端发送的信息
        InputStream is = socket.getInputStream();
        byte[] data = new byte[1024];
        //不确定多少字节，无限循环
        int len = 0;
        while ((len = is.read(data)) != -1) {
            String s = new String(data, 0, len);
            System.out.println("从服务端接收的信息为+" + s);
        }
        socket.shutdownInput();
        socket.close();
    }
}
